<template>
	<view class="container">
		<button class="btns" type="primary" @click="clearData">清除缓存</button>
		<button class="btns" type="primary" @click="loading">更新数据</button>
		<picker @change="bindPickerChange" :value="index" :range="array">
			<button class="btns" type="primary">下载覆盖</button>
		</picker>

		<button class="btns" type="primary" @click="gotoHome">进入首页</button>
		<uni-popup ref="popup" class="popup" :mask-click="false" background-color="#fff">
			<view class="popup-title">{{popueTitle}}</view>
			<view class="progress-box">
				<progress :percent="progress" show-info stroke-width="3" />
			</view>

		</uni-popup>
	</view>
</template>

<script>
	import {
		getInfo,
		setInfo
	} from '@/core/unicommon/storyageInfo.js'
	import {
		downLoad,
		removeSaveFile,
		filesList
	} from '@/core/file/File.js'
	import {

		getSubsurfaceBiomass,
		getGrasslandType,
		getEnvironment,
		getYfList,
		getBiomass,
		getYdList,
		projects,
		organizationTree,
		getBrushSurveyList,
		getFrequencys,
		getRichness

	} from '@/api/system.js'
	export default {
		data() {
			return {
				userinfo: null,
				userdata: null,
				index: 2,
				popueTitle: "下载数据",
				progress: 0,
				array: []
			}
		},
		onLoad(e) {
			let year = (new Date()).getFullYear()
			this.array = [year - 2, year - 1, year]
			getInfo("userinfo").then(res => {
				if (res && res.data) {
					this.userinfo = res.data
				}


			})
			getInfo("userdata").then(res => {
				if (res && res.data) {
					this.userdata = res.data
				}

			})
		},
		methods: {
			async clearData() {
				uni.showLoading({
					title: "清理中",
					mask: true,
					icon: 'loading',
				})
				try {
					uni.removeStorageSync('userdata');
				} catch (e) {

				}
				// #ifdef APP-PLUS
				let fileRes = await filesList()

				for (const file of fileRes) {
					let a = await removeSaveFile(file.filePath)

				}
				// #endif
				uni.hideLoading()

				uni.showToast({
					title: '清理成功',
					icon: 'checkmarkempty'
				})
			},
			bindPickerChange(val) {
				console.log(val, this.index)
				this.array[this.index]
				this.userinfo.year = this.array[this.index]
				setInfo("userinfo", this.userinfo)
				this.download()
			},
			async download() {
				await this.downLoadData(this.userinfo.id, true)
				uni.switchTab({
					url: "/pages/home/home"
				});

			},
			async loading() {
				if (!this.userdata) {
					return uni.showToast({
						title: '请先下载数据，更新数据是为了获取服务上最新数据',
						icon: 'none'
					})
				}
				await this.downLoadData(this.userinfo.id, false)
				uni.switchTab({
					url: "/pages/home/home"
				});
			},
			gotoHome() {
				console.log(this.userdata)
				if (!this.userdata) {

					uni.showModal({
						title: '警告',
						content: '当前没用用户是数据',
						success: function(res) {
							if (res.confirm) {
								uni.switchTab({
									url: "/pages/home/home"
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else {
					uni.switchTab({
						url: "/pages/home/home"
					});
				}

			},
			async downLoadData(userid, type) {
				this.popueTitle = "开始下载工程数据"
				this.toggleOpen()
				this.progress = 0

				let surveyUser = userid
				let projectsRes = await projects({})
				//缓存样地数据
				this.popueTitle = "开始下载样地数据"
				let ydData = await this.downloadyd(surveyUser, type)
				this.progress = 16
				//缓存样方数据
				this.popueTitle = "开始下载样方数据"
				let yfData = await this.downloadyf(surveyUser, type)
				this.progress = 32

				this.popueTitle = "开始下载生物量数据"
				let biomassRes = await this.downloadbiomass(surveyUser, type)
				this.progress = 48

				this.popueTitle = "开始下载温湿度数据"
				let envRes = await this.downloadenv(surveyUser, type)
				this.progress = 64

				this.popueTitle = "开始下载草地类型数据"

				let grassTypeRes = await this.downloadGrassType(surveyUser, type)
				this.progress = 80
				this.popueTitle = "开始下载草地类型数据"
				let subBiomassRes = await this.downloadSubBiomass(surveyUser, type)
				let brushRes = await this.downloadBrush(surveyUser, type)

				let richRes = await this.downloadRich(surveyUser, type)
				let frequencyRes = await this.downloadFrequencys(surveyUser, type)


				let orgTree = await organizationTree()
				this.progress = 100
				//this.toggleClose()

				//下载资源
				this.popueTitle = "开始下载资源数据"
				this.progress = 0
				// this.toggleOpen()
				let imageInfos = []
				imageInfos = imageInfos.concat(ydData.images, yfData.images, biomassRes.images, envRes.images,
					grassTypeRes.images, subBiomassRes.images)
				let fileRes = []
				// #ifdef APP-PLUS	
				fileRes = await this.downLoadfiles(imageInfos)



				//#endif
				//storyage存储
				let userdata = {
					"projects": projectsRes.data.records,
					yd: ydData.data,
					yf: yfData.data,
					grassType: grassTypeRes.data,
					env: envRes.data,
					biomass: biomassRes.data,
					subBiomass: subBiomassRes.data,
					brush: brushRes.data,
					rich: richRes.data,
					frequency: frequencyRes.data,
					org: orgTree.data,
					files: fileRes
				}
				this.userdata = userdata
				uni.setStorageSync("userdata", userdata)
				this.toggleClose()
			},
			async downloadyd(surveyUser, type) {
				let imageInfos = []
				let ydRes = await getYdList({
					surveyUser
				})
				let yd = null
				let ydData = ydRes.data.filter(t => t.ydNumber.substr(0, 4) == this.array[this.index])
				if (type) {
					yd = ydData.map(d => {
						d.action = "none"
						imageInfos = imageInfos.concat(this.getYdzpArr(d))
						return d
					})
				} else { //更新
					console.log(111, this.userdata)
					yd = this.userdata.yd
					ydData.map(d => {
						let olddata = yd.find(t => t.id == d.id)
						if (olddata) {
							if (olddata.action == 'none') {
								olddata = d
							}
						} else {
							d.action = "none"
							imageInfos = imageInfos.concat(this.getYdzpArr())
							yd.push(d)
						}
					})
				}
				return {
					data: yd,
					images: imageInfos
				}
			},
			async downloadyf(surveyUser, type) {
				let yfRes = await getYfList({
					surveyUser
				})
				let yfData = yfRes.data.filter(t => t.ydNumber.substr(0, 4) == this.array[this.index])
				let imageInfos = []
				let yf = null
				if (type) {
					yf = yfData.map(d => {
						d.action = 'none'
						imageInfos = imageInfos.concat(this.getYfzpArr(d))
						return d
					})
				} else {
					yf = this.userdata.yf
					yfData.map(d => {
						let olddata = yf.find(t => t.id == d.id)
						if (olddata) {
							if (olddata.action == 'none') {
								olddata = d
							}
						} else {
							d.action = "none"
							imageInfos = imageInfos.concat(this.getYfzpArr())
							yf.push(d)
						}
					})
				}
				return {
					data: yf,
					images: imageInfos
				}
			},

			async downloadbiomass(surveyUser, type) {
				let imageInfos = []
				let biomass = null
				let biomassRes = await getBiomass({
					surveyUser
				})
				let biomassData = biomassRes.data.filter(t => t.ydNumber.substr(0, 4) == this.array[this.index])
				if (type) {
					biomass = biomassData.map(d => {
						d.action = 'none'
						let zps = this.getyfzpOtther(d, "biomass")
						if (zps && zps.length > 0) {
							imageInfos = imageInfos.concat(zps)
						}

						return d
					})
				} else {
					biomass = this.userdata.biomass
					biomassData.map(d => {
						let olddata = biomass.find(t => t.id == d.id)
						if (olddata) {
							if (olddata.action == 'none') {
								olddata = d
							}
						} else {
							d.action = "none"
							let zps = this.getyfzpOtther(d, "biomass")
							if (zps && zps.length > 0) {
								imageInfos = imageInfos.concat(zps)
							}
							biomass.push(d)
						}
					})
				}
				return {
					data: biomass,
					images: imageInfos
				}
			},
			async downloadenv(surveyUser, type) {
				let envRes = await getEnvironment({
					surveyUser
				})
				let envData = envRes.data.filter(t => t.ydNumber.substr(0, 4) == this.array[this.index])
				let env = null
				let imageInfos = []
				if (type) {
					env = envData.map(d => {
						d.action = 'none'
						let zps = this.getyfzpOtther(d, "env")
						if (zps && zps.length > 0) {
							imageInfos = imageInfos.concat(zps)
						}
						return d
					})
				} else {
					env = this.userdata.env
					envData.map(d => {
						let olddata = env.find(t => t.id == d.id)
						if (olddata) {
							if (olddata.action == 'none') {
								olddata = d
							}
						} else {
							d.action = "none"
							let zps = this.getyfzpOtther(d, "env")
							if (zps && zps.length > 0) {
								imageInfos = imageInfos.concat(zps)
							}
							env.push(d)
						}
					})
				}
				return {
					data: env,
					images: imageInfos
				}
			},
			async downloadGrassType(surveyUser, type) {

				let grassTypeRes = await getGrasslandType({
					surveyUser
				})
				let grassTypeData = grassTypeRes.data.filter(t => t.ydNumber.substr(0, 4) == this.array[this.index])
				let grassType = null
				let imageInfos = []
				if (type) {
					grassType = grassTypeData.map(d => {
						d.action = 'none'

						let zps = this.getyfzpOtther(d, "grassType")
						if (zps && zps.length > 0) {
							imageInfos = imageInfos.concat(zps)
						}
						return d
					})
				} else {
					grassType = this.userdata.grassType
					grassTypeData.map(d => {
						let olddata = grassType.find(t => t.id == d.id)
						if (olddata) {
							if (olddata.action == 'none') {
								olddata = d
							}
						} else {
							d.action = "none"
							let zps = this.getyfzpOtther(d, "grassType")
							if (zps && zps.length > 0) {
								imageInfos = imageInfos.concat(zps)
							}
							grassType.push(d)
						}
					})
				}
				return {
					data: grassType,
					images: imageInfos
				}

			},
			async downloadSubBiomass(surveyUser, type) {
				//底下生物量
				let subBiomassRes = await getSubsurfaceBiomass({
					surveyUser
				})
				let subBiomassData = subBiomassRes.data.filter(t => t.ydNumber.substr(0, 4) == this.array[this.index])
				let subBiomass = null
				let imageInfos = []
				if (type) {
					subBiomass = subBiomassData.map(d => {
						d.action = 'none'

						let zps = this.getyfzpOtther(d, "subBiomass")
						if (zps && zps.length > 0) {
							imageInfos = imageInfos.concat(zps)
						}
						return d
					})
				} else {
					subBiomass = this.userdata.subBiomass
					subBiomassData.map(d => {
						let olddata = subBiomass.find(t => t.id == d.id)
						if (olddata) {
							if (olddata.action == 'none') {
								olddata = d
							}
						} else {
							d.action = "none"
							let zps = this.getyfzpOtther(d, "subBiomass")
							if (zps && zps.length > 0) {
								imageInfos = imageInfos.concat(zps)
							}
							subBiomass.push(d)
						}
					})
				}
				return {
					data: subBiomass,
					images: imageInfos
				}

			},
			async downloadBrush(surveyUser, type) {
				//底下生物量
				let brushRes = await getBrushSurveyList({
					surveyUser
				})
				let brushData = brushRes.data.filter(t => t.ydNumber.substr(0, 4) == this.array[this.index])
				let brush = null

				if (type) {
					brush = brushData.map(d => {
						d.action = 'none'
						return d
					})
				} else {
					brush = this.userdata.brush
					brushData.map(d => {
						let olddata = brush.find(t => t.id == d.id)
						if (olddata) {
							if (olddata.action == 'none') {
								olddata = d
							}
						} else {
							d.action = "none"

							brush.push(d)
						}
					})
				}
				return {
					data: brush,
				}
			},
			async downloadFrequencys(surveyUser, type) {
				//底下生物量
				let frequencyRes = await getFrequencys({
					surveyUser
				})
				let frequencyData = frequencyRes.data.filter(t => t.ydNumber.substr(0, 4) == this.array[this.index])
				let frequency = null
				if (type) {
					frequency = frequencyData.map(d => {
						d.action = 'none'
						return d
					})
				} else {
					frequency = this.userdata.frequency
					frequencyData.map(d => {
						let olddata = frequency.find(t => t.id == d.id)
						if (olddata) {
							if (olddata.action == 'none') {
								olddata = d
							}
						} else {
							d.action = "none"

							frequency.push(d)
						}
					})
				}
				return {
					data: frequency,

				}

			},
			async downloadRich(surveyUser, type) {
				//底下生物量
				let brushRes = await getRichness({
					surveyUser
				})
				let brushData = brushRes.data.filter(t => t.ydNumber.substr(0, 4) == this.array[this.index])
				let brush = null

				if (type) {
					brush = brushData.map(d => {
						d.action = 'none'
						return d
					})
				} else {
					brush = this.userdata.rich
					brushData.map(d => {
						let olddata = brush.find(t => t.id == d.id)
						if (olddata) {
							if (olddata.action == 'none') {
								olddata = d
							}
						} else {
							d.action = "none"

							brush.push(d)
						}
					})
				}
				return {
					data: brush,

				}

			},

			getYdzpArr(d) {
				if (!d) return []
				let imageInfos = []
				let fqzp = []
				if (d.fqqzp) {
					fqzp = JSON.parse(d.fqqzp)
					fqzp.map(t => {
						t.type = "yd"
						t.ydNumber = d.ydNumber
						t.yfNumber = null
						return t
					})
				}
				let sqzp = []
				if (d.sqzp) {
					sqzp = JSON.parse(d.sqzp)
					sqzp.map(t => {
						t.type = "yd"
						t.ydNumber = d.ydNumber
						t.yfNumber = null
						return t
					})
				}
				let khzp = []
				if (d.khqzp) {
					khzp = JSON.parse(d.khqzp)
					khzp.map(t => {
						t.type = "yd"
						t.ydNumber = d.ydNumber
						t.yfNumber = null
						return t
					})
				}
				return imageInfos.concat(fqzp, sqzp, khzp)
			},
			getYfzpArr(d) {
				if (!d) return []
				let fqzp = [],
					sqzp = [],
					khzp = [],
					yfzp = [],
					imageInfos = []
				if (d.fqqyfzp) {
					fqzp = JSON.parse(d.fqqyfzp)

					fqzp.map(t => {
						t.type = "yf"
						t.ydNumber = d.ydNumber
						t.yfNumber = d.yfNumber
						return t
					})
				}
				if (d.sqyfzp) {
					sqzp = JSON.parse(d.sqyfzp)
					sqzp.map(t => {
						t.type = "yf"
						t.ydNumber = d.ydNumber
						t.yfNumber = d.yfNumber
						return t
					})
				}
				if (d.khyfzp) {
					khzp = JSON.parse(d.khyfzp)
					khzp.map(t => {
						t.type = "yf"
						t.ydNumber = d.ydNumber
						t.yfNumber = d.yfNumber
						return t
					})
				}
				if (d.yfzp) {
					yfzp = JSON.parse(d.yfzp)
					yfzp.map(t => {
						t.type = "yf"
						t.ydNumber = d.ydNumber
						t.yfNumber = d.yfNumber
						return t
					})
				}
				return imageInfos.concat(fqzp, sqzp, khzp, yfzp)
			},
			getyfzpOtther(d, type) {
				if (!d) return []
				let imageInfos = []
				if (d.yfzp) {
					let zp = JSON.parse(d.yfzp)

					zp.map(t => {
						t.type = type
						t.ydNumber = d.ydNumber
						t.yfNumber = d.yfNumber
						return t
					})
					console.log(zp)
					return imageInfos.concat(zp)

				}
			},


			async downLoadfiles(data) {
				let dataInfo = []
				let rate = 100 / data.length
				let index = 0
				let that = this
				for (const d of data) {
					console.log(d)
					if (!d.url) {
						continue
					}
					let dres = await downLoad(d.url)
					index++
					that.progress = Math.round(index * rate)
					if (dres) {
						let file = {
							name: d.name,
							uid: d.uid,
							url: d.url,
							localurl: dres.savedFilePath,
							action: 'none',
							type: d.type,
							ydNumber: d.ydNumber,
							yfNumber: d.yfNumber,
							id: (new Date()).getTime()
						}
						dataInfo.push(file)
					}
				}
				return dataInfo

			},
			toggleOpen() {
				this.$refs.popup.open('center')
			},
			toggleClose() {
				this.$refs.popup.close()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		margin: 30% 60rpx;

	}

	.btns {
		margin-top: 40rpx;
	}

	.popup {
		width: 100%;
		height: 100rpx;
	}

	.progress-box {
		width: 100vw;
		// width: 100%;
		display: flex;
		height: 50rpx;

	}
</style>